package com.admin.web.uresponse;

import com.bayss.core.DokoServerException;
import com.bayss.core.DokoServerExceptionFactor;
import com.bayss.core.entity.rbac.OBGUserInfo;
import com.bayss.core.service.user.ObgUserService;
import com.bayss.core.util.TokenUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

@Component
public class UserResolver implements HandlerMethodArgumentResolver {
    private ObgUserService obgUserService;

    @Autowired
    public void setObgUserService(ObgUserService obgUserService) {
        this.obgUserService = obgUserService;
    }
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType() == OBGUserResponse.class;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
        String token = servletRequest.getHeader("token");// 从 http 请求头中取出 token
        Integer userId = TokenUtils.getUserId(token, "user_id");
        OBGUserInfo obgUserInfo = obgUserService.getUser(userId);
        if (obgUserInfo == null) {
            throw new DokoServerException(DokoServerExceptionFactor.token_expire, "用户不存在");
        }

        OBGUserResponse user = new OBGUserResponse(obgUserInfo,userId);
        return user;
    }
}
